package com.tech.koufu.ui.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.CompetitionGroup;
import com.tech.koufu.model.CompetitionGroupDetail;
import com.tech.koufu.model.CompetitionNotice;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.adapter.RankCompetorAdapter; 
import com.tech.koufu.ui.widiget.CofDialog;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 比赛详情页面
 * @author jl_luo
 *
 */
public class CompetitionDetailActivity extends Activity implements OnClickListener{
	private static final String TAG = CompetitionDetailActivity.class.getName();
	private Context mContext;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView; 
	private RankCompetorAdapter mAdapter;
	
	private CompetitionGroup mCompetitionGroup;
	private CompetitionGroupDetail mCompetitionGroupDetail;
	
	private RequestQueue mQueue; 
	private MyApplication myApp;
	CookieStringRequest stringRequest,attendRequest;
	private TextView txt_comp_notice,txt_competition_founder,txt_comp_notice_title;
	private TextView competition_begtime,competition_endtime;
	private Button btn_attend_competition;
	private CofDialog cofDialog;
	private String isAnswer = "no";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_competition);
		mContext = this;
		initView();
	}
	
	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	private void initView() { 
		findViewById(R.id.btn_refresh).setVisibility(View.GONE);
		findViewById(R.id.img_callback).setOnClickListener(this);
		btn_attend_competition = (Button)findViewById(R.id.btn_attend_competition);
		btn_attend_competition.setOnClickListener(this);
		btn_attend_competition.setVisibility(View.INVISIBLE);
		((TextView)findViewById(R.id.tv_title)).setText(R.string.top_detail_competition);;
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
        registerForContextMenu(actualListView);
        txt_comp_notice = (TextView)findViewById(R.id.txt_comp_notice); 
        txt_competition_founder = (TextView)findViewById(R.id.txt_competition_founder);
        competition_begtime = (TextView)findViewById(R.id.competition_begtime);
        competition_endtime = (TextView)findViewById(R.id.competition_endtime);
        txt_comp_notice_title = (TextView)findViewById(R.id.txt_comp_notice_title);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				loadCompetitor();
			}
		});
        initData();
	}

	private void initData() {
		mCompetitionGroup = getIntent().getParcelableExtra("cgBean");
		show();
		myApp = (MyApplication)getApplication();
		mQueue = Volley.newRequestQueue(getApplicationContext());  
		mAdapter = new RankCompetorAdapter(getApplicationContext());
		actualListView.setAdapter(mAdapter);
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
	}
	private void show(){
		if(mCompetitionGroup!=null){
			txt_comp_notice_title.setText(mCompetitionGroup.name); 
			if(mCompetitionGroup.notices!=null && mCompetitionGroup.notices.size()>0){
				CompetitionNotice notice = mCompetitionGroup.notices.get(0);
				txt_comp_notice.setText(Html.fromHtml(notice.content)); 
//				txt_comp_notice_title.setText(notice.title);
			}
			txt_competition_founder.setText(String.format(getResources().getString(R.string.competition_founder_tt), mCompetitionGroup.userName));
		}
	}
	private void showGroup(){
		if(mCompetitionGroupDetail!=null){
			competition_begtime.setText(mCompetitionGroupDetail.startTime);
			competition_endtime.setText(mCompetitionGroupDetail.endTime);
			if(!mCompetitionGroupDetail.isMember.equals("no")){
				btn_attend_competition.setVisibility(View.GONE);
			}else{
				btn_attend_competition.setVisibility(View.VISIBLE);
			}
		}
	}
	private void loadCompetitor(){
		String url = Statics.URL_PHP+Statics.IF_GROUPDETAIL; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try { 
						Log.d(TAG, response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONObject gd = obj.getJSONObject("data"); 
							mCompetitionGroupDetail = new CompetitionGroupDetail(gd); 
							mCompetitionGroupDetail.groupId = mCompetitionGroup.groupId;
							showGroup(); 
							mAdapter.datas = mCompetitionGroupDetail.groupUsers;
							if(mAdapter.datas!=null){
								mAdapter.notifyDataSetChanged();   
							}
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("group_id", mCompetitionGroup.groupId);    
				return params;
			}
		}; 
		stringRequest.setHeader(myApp.phpsessid);
		mQueue.add(stringRequest);
	}
	
	private void joinGroup(){
		String url = Statics.URL_PHP+Statics.IF_joinGroup; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try { 
						Log.d(TAG, response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String info = obj.optString("info");
						if(status.equals("0")){//成功 
							btn_attend_competition.setVisibility(View.GONE); 
							Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
						}else if(status.equals("1")){ 
							if(info!=null && info.equals("needQuestion")){
								//答问题
								//reg_question reg_answer
								String reg_question = obj.optString("reg_question");
								String reg_answer = obj.optString("reg_answer");
								showReqDiaolog(reg_question,reg_answer);
							}
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("group_id", mCompetitionGroup.groupId);    
				if(isAnswer.equals("right")){
					params.put("answer", "right");    
				}
				return params;
			}
		}; 
		stringRequest.setHeader(myApp.phpsessid);
		mQueue.add(stringRequest);
	}
	private void showReqDiaolog(String message,final String answer){
		if(cofDialog==null){
			cofDialog = new CofDialog(getApplicationContext(), message, answer);
			
			cofDialog.positive.setOnClickListener(new View.OnClickListener() { 
				@Override
				public void onClick(View v) { 
					String _answer = cofDialog.getAnswer();
					if(_answer!=null){
						if(_answer == answer){
							joinGroup();
							cofDialog.dismiss();
						}else{
							Toast.makeText(getApplicationContext(), "回答错误", Toast.LENGTH_SHORT).show();
						}
					}else{
						Toast.makeText(getApplicationContext(), "回答错误", Toast.LENGTH_SHORT).show();
					}
				}
			});
			cofDialog.negative.setOnClickListener(new View.OnClickListener() { 
				@Override
				public void onClick(View v) {
					cofDialog.dismiss(); 
				}
			});
		}
		cofDialog.show();  
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_attend_competition:
			if(mCompetitionGroupDetail.isMember.equals("no")){
				joinGroup();
			}
			break;

		default:
			break;
		}
	}
	@Override
	protected void onStop() { 
		super.onStop();
		if(stringRequest!=null){
			mQueue.cancelAll(stringRequest);
		}
		if(attendRequest!=null){
			mQueue.cancelAll(attendRequest);
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if(keyCode == KeyEvent.KEYCODE_BACK){
			 this.finish();
			 return true;
		 }
		return super.onKeyDown(keyCode, event);
	}
}
